<template>
  <view class="container">
    <view class="order-relet-content">
      <summary-info title="租赁信息" :summaryList="summaryLease" :defaultFold="false">
        <template #leasePeriod>
          <view class="lease-period">
            <view class="lease-period-val">{{
              orderInfo.expectedUseCarTime ? `${orderInfo.expectedUseCarTime} - ${orderInfo.expectedReturnCarTime}` : '-'
            }}</view>
            <view class="lease-period-rentdays" v-if="orderInfo.leaseNumberStr">租期：{{ orderInfo.leaseNumberStr }}</view>
          </view>
        </template>
      </summary-info>
      <summary-info title="交车信息" :summaryList="summaryCarInfo" />
      <box-info :carId="orderInfo.carId"></box-info>
      <ve-form :model="form" :rules="rules" ref="formRef">
        <!-- <contract-card :showFold="true" :defaultFold="false" /> -->
        <ve-card title="还车信息" :class="[!returnCarInfoFold ? 'give-car-info-folded' : '']" fold v-model:initFold="returnCarInfoFold">
          <template #forever-show="{ contentIsShow }">
            <ve-form-item required prop="returnStaffId" label="还车人">
              <remote-select
                v-model="form.returnStaffId"
                v-model:label="form.returnStaffName"
                :params="{
                  oldId: defaultStaffId ? defaultStaffId : undefined,
                  siteIdList: [orderInfo.returnSiteId],
                }"
                type="staff_all_bysite"
              />
            </ve-form-item>
            <ve-form-item required prop="returnCarTime" :borderBottom="contentIsShow" label="还车时间">
              <ve-date-picker v-model="form.returnCarTime" :minDate="prevGivecarTime" mode="datetime" @confirm="returnCarTimeChangeFn" />
            </ve-form-item>
          </template>
          <ve-form-item label="还车里程" unit="公里" required prop="returnCarMileage">
            <ve-input-number :precision="0" :min="prevGivecarMileage" v-model="form.returnCarMileage" @confirm="endCarMileChangeFn" />
          </ve-form-item>
          <ve-form-item label="还车油(电)量" required prop="returnFuelNum">
            <ve-input-number :precision="0" :min="1" :max="99999" v-model="form.returnFuelNum" />
          </ve-form-item>
          <ve-form-item label="还车照片" labelPosition="top">
            <ve-upload v-model="form.returnFileIds" />
          </ve-form-item>
          <ve-form-item label="还车视频" labelPosition="top">
            <ve-upload-video v-model="form.returnVideoFileIds" :readonly="false" />
          </ve-form-item>
          <ve-form-item label="还车备注" :borderBottom="false" labelPosition="top">
            <ve-input type="textarea" v-model="form.useEndRemark" :maxlength="200" />
          </ve-form-item>
        </ve-card>
      </ve-form>
      <!-- 费用信息 -->
      <view class="fee-pane-content">
        <ve-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <ve-card title="还车费用" fold :defaultFold="false">
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane :orderFeeIndex="index" :inlineCard="true" :disabledOnlineFee="true">
                <template #returnDepositFee>
                  <return-deposit :orderId="orderInfo.id" />
                </template>
              </fee-pane>
            </template>
          </ve-card>
        </ve-form>
      </view>
    </view>
    <footer-box id="footer-box">
      <template #extra>
        <feeStatistic />
      </template>
      <ve-button type="primary" size="long" :loading="okLoading" @click="submitFn">完成还车</ve-button>
    </footer-box>
  </view>
  <!-- 查询当前订单的还车车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>
<script setup name="ShortOrderReturnCar">
  import { ref, provide, computed } from 'vue'
  import { getOrdrDetailsAPI, calcPriceAPI, returnCarAPI } from '@/api/order/lOrder'
  import { checkExistEtcOrderApi } from '@/api/order/sOrder'
  import finishEtcOrderModal from '../components/finish-etc-order-modal.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../../work/workOrder/form/shortOrder/components/box-info.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import returnDeposit from './components/return-car/return-deposit.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { onLoad } from '@dcloudio/uni-app'
  import { getUserInfo } from './tools'
  const { foldValidate } = useFormFold([])
  import useToast from '@/hooks/useToast'
  import contractCard from './components/contract/contract-card.vue'
  import { handleContracList } from './tools'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'

  // 获取会员Store
  const returnCarInfoFold = ref(true)
  const form = ref({})
  const orderInfo = ref({})
  const memberInfo = ref({})
  const orderId = ref()
  const defaultStaffId = ref()
  const defaultStaffName = ref()
  onLoad((options) => {
    orderId.value = options.id
    form.value = {
      id: orderId.value,
      returnCarTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      depositDeductFlag: 0,
      changeDepositFlag: 0,
    }
    // 获取订单详情
    getOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      // 车务专员 | 当前登录者 id
      handleDefaultStaff()
      // 合同信息
      let contractList = handleContracList(orderInfo.value.contractList || [])
      form.value.contractList = contractList

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 初始化 超里程费和超时费
        calcDefaultFee('returnCarTime')
      })
    })
  })
  const rules = computed(() => {
    let _rule = {
      returnStaffId: [{ required: true, message: '请选择还车人' }],
      returnCarTime: [{ required: true, message: '请选择还车时间' }],
      returnCarMileage: [{ required: true, message: '请输入还车里程' }],
      returnFuelNum: [{ required: true, message: '请输入还车油(电)量' }],
    }
    let formValue = form.value
    if (formValue.contractList) {
      formValue.contractList.forEach((contract, index) => {
        if (contract.fileId) {
          _rule[`contractList.${index}.contractNo`] = [{ required: true, message: '请输入合同编号' }]
        }
      })
    }
    return _rule
  })
  const prevOrderCarInfo = computed(() => {
    let lastOrderCarInfo = {}
    let longOrderCarInfoDtos = orderInfo.value.longOrderCarInfoDtos
    if (longOrderCarInfoDtos && longOrderCarInfoDtos.length) {
      lastOrderCarInfo = longOrderCarInfoDtos[longOrderCarInfoDtos.length - 1]
    }
    return lastOrderCarInfo
  })
  const prevGivecarMileage = computed(() => {
    return prevOrderCarInfo.value.giveCarMileage
  })
  const prevGivecarTime = computed(() => {
    return prevOrderCarInfo.value.giveCarTime
  })

  const formRef = ref()
  provide('form', form)

  // 顶部统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      { label: '预计租赁周期', slotName: 'leasePeriod' },
      { label: '交车车牌号', value: orderInfoVal.licenseNo },
      { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
      { label: '预订车型', value: orderInfoVal.originalModelName },
      { label: '交车车型', value: orderInfoVal.modelName },
    ]
  })
  const summaryCarInfo = computed(() => {
    const orderCarInfos = orderInfo.value.longOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return [
      {
        label: '交车里程',
        value: lastOrderCarInfo.giveCarMileage ? lastOrderCarInfo.giveCarMileage + ' 公里' : '',
      },
      { label: '交车油(电)量', value: lastOrderCarInfo.giveFuelAmount },
    ]
  })

  // 处理员工默认值
  const handleDefaultStaff = () => {
    new Promise((resolve) => {
      if (orderInfo.value.returnStaffId) {
        resolve({
          employeeId: orderInfo.value.returnStaffId,
          employeeName: orderInfo.value.returnStaffName,
        })
      } else {
        getUserInfo().then((res) => {
          resolve(res)
        })
      }
    }).then(({ employeeId, employeeName }) => {
      defaultStaffId.value = employeeId
      defaultStaffName.value = employeeName
      // 默认交车人
      form.value.returnStaffId = defaultStaffId.value
      form.value.returnStaffName = defaultStaffName.value
      console.log(employeeId, employeeName)
    })
  }
  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee', 'returnRefuseFee', 'returnDepositFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const endCarMileChangeFn = () => {
    calcDefaultFee('endCarMile')
  }
  const returnCarTimeChangeFn = () => {
    calcDefaultFee('returnCarTime')
  }
  // 计算默认费用
  const calcDefaultFee = (type) => {
    const param = {
      endTime: form.value.returnCarTime,
      returnCarMileage: form.value.returnCarMileage,
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      type: 2,
    }
    calcPriceAPI(param).then((res) => {
      const result = res.result
      const otherPrice = result.otherPrice
      if (otherPrice) {
        let feeDetailList = feeForm.value.orderFee[0].feeDetailList
        feeDetailList.forEach((feeCategory) => {
          if (feeCategory.type == 'extraFee') {
            let childrenList = feeCategory.childrenList
            childrenList.forEach((feeItem) => {
              if (feeItem.itemName == '超里程费') {
                if (type == 'endCarMile') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超里程费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
              if (feeItem.itemName == '超时费') {
                if (type == 'returnCarTime') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超时费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
            })
          }
        })
      }
    })
  }
  // 还车确认
  const okLoading = ref(false)
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    okLoading.value = true
    returnCarAPI(param)
      .then(() => {
        useToast({
          title: '还车成功',
        }).then(() => {
          useLoadDataAndHotUpdateNavigateBack()
        })
      })
      .catch(() => {
        okLoading.value = false
      })
  }
  // 检验还车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    formRef.value.validate((valid, errors) => {
      if (valid) {
        let params = {
          refType: 2,
          refId: form.value.id,
          carId: orderInfo.value.carId,
          endTime: form.value.returnCarTime,
        }
        checkExistEtcOrderApi(params).then((res) => {
          let result = res.result
          if (result.existOrder) {
            let params = {
              carLicenseNo: orderInfo.value.licenseNo,
              operateStr: '还车',
            }
            etcModalRef.value.open(params)
          } else {
            submitOperateFn()
          }
        })
      } else {
        foldValidate(errors, true)
      }
    })
  }
</script>
<style lang="less" scoped>
  .container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    .order-relet-content {
      padding: 24rpx;
      padding-bottom: 254rpx;
    }
  }
  .lease-period-rentdays {
    font-size: 30rpx;
    color: #3072f6;
    margin-top: 8rpx;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: right;
    color: #3072f6;
  }
  .member-name {
    display: flex;
    align-items: flex-start;
    .ve-button {
      position: relative;
      height: 56rpx;
      margin-left: 6rpx;
      margin-top: -8rpx;
    }
  }

  .fee-pane-content {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }

  #footer-box {
    height: 250rpx;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 100;
  }
  .give-car-info-folded {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }
</style>
